<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="设备系统" prop="deviceSystem">
              <el-input v-model="queryParams.deviceSystem" placeholder="请输入设备系统" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="厂家" prop="factory">
              <el-input v-model="queryParams.factory" placeholder="请输入厂家" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="queryParams.brand" placeholder="请输入品牌" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="型号" prop="model">
              <el-input v-model="queryParams.model" placeholder="请输入型号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="规格" prop="specifications">
              <el-input v-model="queryParams.specifications" placeholder="请输入规格" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="数量" prop="number">
              <el-input v-model="queryParams.number" placeholder="请输入数量" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="来源" prop="source">
              <el-input v-model="queryParams.source" placeholder="请输入来源" clearable @keyup.enter="handleQuery" />
            </el-form-item>
<!--            <el-form-item label="工单id" prop="workorderId">-->
<!--              <el-input v-model="queryParams.workorderId" placeholder="请输入工单id" clearable @keyup.enter="handleQuery" />-->
<!--            </el-form-item>-->
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['workorder:partsRequipment:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['workorder:partsRequipment:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['workorder:partsRequipment:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['workorder:partsRequipment:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="partsRequipmentList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" align="center" width="60" />
        <el-table-column label="设备系统" align="center" prop="deviceSystem">
          <template #default="scope">
            <span>{{ getDeviceSystemName(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="设备类型" align="center" prop="deviceType" >
          <template #default="scope">
            <span>{{ getDeviceTypeName(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="厂家" align="center" prop="factory" />
        <el-table-column label="品牌" align="center" prop="brand" />
        <el-table-column label="型号" align="center" prop="model" />
        <el-table-column label="规格" align="center" prop="specifications" />
        <el-table-column label="数量" align="center" prop="number" />
        <el-table-column label="来源" align="center" prop="source" />
<!--        <el-table-column label="状态" align="center" prop="status" />-->
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template #default="scope">
            <dict-tag :options="parts_requipment_status" :value="scope.row.status" />
          </template>
        </el-table-column>
<!--        <el-table-column label="工单id" align="center" prop="workorderId" />-->
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['workorder:partsRequipment:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="签收" placement="top">
              <el-button link type="primary" v-if="scope.row.status == '0'" icon="Check" @click="handleReceipt(scope.row)" v-hasPermi="['workorder:partsRequipment:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['workorder:partsRequipment:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改备件需求对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="partsRequipmentFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="系统名称" prop="deviceSystem">
          <el-input v-model="form.deviceSystem" placeholder="请输入设备系统" />
        </el-form-item>
        <el-form-item label="设备类型" prop="deviceType">
          <el-input v-model="form.deviceType" placeholder="请输入设备类型" />
        </el-form-item>
        <el-form-item label="厂家" prop="factory">
          <el-input v-model="form.factory" placeholder="请输入厂家" />
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-input v-model="form.brand" placeholder="请输入品牌" />
        </el-form-item>
        <el-form-item label="型号" prop="model">
          <el-input v-model="form.model" placeholder="请输入型号" />
        </el-form-item>
        <el-form-item label="规格" prop="specifications">
          <el-input v-model="form.specifications" placeholder="请输入规格" />
        </el-form-item>
        <el-form-item label="数量" prop="number">
          <el-input v-model="form.number" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="来源" prop="source">
          <el-input v-model="form.source" placeholder="请输入来源" />
        </el-form-item>
        <el-form-item label="工单id" prop="workorderId">
          <el-input v-model="form.workorderId" placeholder="请输入工单id" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PartsRequipment" lang="ts">
import { listPartsRequipment, getPartsRequipment, delPartsRequipment, addPartsRequipment, updatePartsRequipment,execReceipt } from '@/api/workorder/partsRequipment';
import { PartsRequipmentVO, PartsRequipmentQuery, PartsRequipmentForm } from '@/api/workorder/partsRequipment/types';
import { reactive, ref, toRefs } from 'vue';
import { listDeviceSystem } from '@/api/workorder/deviceSystem';
import { listDeviceType } from '@/api/workorder/deviceType';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const partsRequipmentList = ref<PartsRequipmentVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const partsRequipmentFormRef = ref<ElFormInstance>();
const { parts_requipment_status } = toRefs<any>(proxy?.useDict('parts_requipment_status'));


const queryData = reactive({
  deviceSystemParams: {
    pageNum: 1,
    pageSize: 999,
    description: undefined,
    systemId: undefined
  },
});
const { deviceSystemParams } = toRefs(queryData);
const deviceSystemList = ref<Array<{ id: string | number, systemName: string }>>([]);
const deviceTypeList = ref<Array<{ id: string | number, typeName: string }>>([]);

//初始化字典数据
// 获取系统类型列表
const getDeviceSystemList = async () => {
  try {
    const res = await listDeviceSystem(deviceSystemParams.value);
    deviceSystemList.value = res.rows;
  } catch (error) {
    console.error('获取系统类型列表失败', error);
  }
};
// 获取设备类型列表
const getDeviceTypeList = async () => {
  try {
    const res = await listDeviceType(deviceSystemParams.value);
    deviceTypeList.value = res.rows;
  } catch (error) {
    console.error('获取设备类型列表失败', error);
  }
};

const getDeviceSystemName = (row?: PartsRequipmentVO) => {
  const deviceSystem = deviceSystemList.value.find(item => item.id === row?.deviceSystem);
  return deviceSystem ? deviceSystem.systemName : '';
};

const getDeviceTypeName = (row?: PartsRequipmentVO) => {
  const deviceType = deviceTypeList.value.find(item => item.id === row?.deviceType);
  return deviceType ? deviceType.typeName : '';
};



const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: PartsRequipmentForm = {
  id: undefined,
  deviceSystem: undefined,
  deviceType: undefined,
  factory: undefined,
  brand: undefined,
  model: undefined,
  specifications: undefined,
  number: undefined,
  source: undefined,
  status: undefined,
  workorderId: undefined,
  remark: undefined
}
const data = reactive<PageData<PartsRequipmentForm, PartsRequipmentQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deviceSystem: undefined,
    deviceType: undefined,
    factory: undefined,
    brand: undefined,
    model: undefined,
    specifications: undefined,
    number: undefined,
    source: undefined,
    status: undefined,
    workorderId: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "Id不能为空", trigger: "blur" }
    ],
    deviceSystem: [
      { required: true, message: "设备系统不能为空", trigger: "blur" }
    ],
    deviceType: [
      { required: true, message: "设备类型不能为空", trigger: "change" }
    ],
    factory: [
      { required: true, message: "厂家不能为空", trigger: "blur" }
    ],
    brand: [
      { required: true, message: "品牌不能为空", trigger: "blur" }
    ],
    model: [
      { required: true, message: "型号不能为空", trigger: "blur" }
    ],
    specifications: [
      { required: true, message: "规格不能为空", trigger: "blur" }
    ],
    number: [
      { required: true, message: "数量不能为空", trigger: "blur" }
    ],
    source: [
      { required: true, message: "来源不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
    workorderId: [
      { required: true, message: "工单id不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询备件需求列表 */
const getList = async () => {
  loading.value = true;
  const res = await listPartsRequipment(queryParams.value);
  partsRequipmentList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  partsRequipmentFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: PartsRequipmentVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加备件需求";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: PartsRequipmentVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getPartsRequipment(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改备件需求";
}

const handleReceipt = async (row?: PartsRequipmentVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await execReceipt(_id);
  if (res.code === 200) {
    proxy?.$modal.msgSuccess("签收成功");
  }else {
    proxy?.$modal.msgError("签收失败");
  }
  await getList();
}

/** 提交按钮 */
const submitForm = () => {
  partsRequipmentFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updatePartsRequipment(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addPartsRequipment(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: PartsRequipmentVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除备件需求编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delPartsRequipment(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('workorder/partsRequipment/export', {
    ...queryParams.value
  }, `partsRequipment_${new Date().getTime()}.xlsx`)
}

onBeforeMount(async () => {
  getDeviceSystemList();
  getDeviceTypeList();
});

onMounted( () => {
  getList();
});
</script>
